import { device } from "../../api";
const debug = process.env.NODE_ENV !== "production";

const MUTATION_TYPES = {
  DEVICE: "DEVICE"
};

const state = {
  devices: {}
};

const getters = {

};

const mutations = {
  [MUTATION_TYPES.DEVICE] (state, device) {
    const devices = { ...state.devices };
    devices[device.deviceNo] = device;
    state.devices = devices;
  }
};


class DeviceLoader {
  #deviceNos = []
  add (deviceNo) {
    const deviceNoSet = new Set(this.#deviceNos);
    deviceNoSet.add(deviceNo);
    this.#deviceNos = [...deviceNoSet];
  }
  async load (commit) {
    const deviceNo = this.#deviceNos.pop();
    if (!deviceNo) {
      return
    }
    const response = await device.load(deviceNo, 1);
    if (response?.code === 0) {
      const device = { ...response.data, deviceNo }
      commit(MUTATION_TYPES.DEVICE, device);
      return response.data
    }
  }
  async orderPosition (commit, { signTime }) {
    const deviceNo = this.#deviceNos.pop();
    if (!deviceNo) {
      return
    }
    const response = await device.orderPosition({ devCode: deviceNo, signTime });
    if (response?.code === 0) {
      const device = { ...response.data, deviceNo }
      commit(MUTATION_TYPES.DEVICE, device);
      return response.data
    }
  }

  async OrderExpress (commit, { phone }) {
    const deviceNo = this.#deviceNos.pop();
    if (!deviceNo) {
      return
    }
    const response = await device.OrderExpress({ code: deviceNo, phone });
    if (response?.code === 0) {
      const device = { positionAddress: response.data, deviceNo }
      commit(MUTATION_TYPES.DEVICE, device);
      return response.data
    }
  }
}

const LOADER = new DeviceLoader();

const actions = {
  async load ({ commit }, { deviceNo }) {
    LOADER.add(deviceNo)
    setTimeout(() => LOADER.load(commit), 300)
  },
  async orderPosition ({ commit }, { devCode, signTime }) {
    LOADER.add(devCode)
    setTimeout(() => LOADER.orderPosition(commit, { signTime }), 300)
  },
  async OrderExpress ({ commit }, { code, phone }) {
    LOADER.add(code)
    setTimeout(() => LOADER.OrderExpress(commit, { phone }), 300)
  },
};

export default {
  strict: debug,
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
